package club.caihappy.server.controller;

import club.caihappy.server.pojo.Admin;
import club.caihappy.server.pojo.RespBean;
import club.caihappy.server.service.IAdminService;
import club.caihappy.server.utils.FastDFSUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * Created by DELL on 2022/10/10
 **/
@RestController
@RequestMapping("admin")
public class AdminInfoController {

    @Autowired
    private IAdminService adminService;

    @Autowired
    private FastDFSUtils fastDFSUtils;

    @ApiOperation("更新用户信息")
    @PutMapping("info")
    public RespBean updateAdmin(@RequestBody Admin admin, Authentication authentication) {
        if (adminService.updateById(admin)) {
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(admin, null, authentication.getAuthorities()));
            return RespBean.success("更新成功");
        }
        return RespBean.error("更新失败");
    }

    @ApiOperation("更新用户密码")
    @PutMapping("pwd")
    public RespBean updateAdminPwd(@RequestBody Map<String, Object> info) {
        String oldPwd = (String) info.get("oldPwd");
        String newPwd = (String) info.get("newPwd");
        String adminId = (String) info.get("adminId");
        return adminService.updatePwdById(oldPwd, newPwd, adminId);
    }

    @ApiOperation("更新用户头像")
    @PostMapping("userface")
    public RespBean updateAdminUserface(@RequestPart("file") MultipartFile file, Integer id, Authentication authentication) {
        String filepath = fastDFSUtils.uploadImage(file);
        return adminService.updateAdminUserface(filepath, id, authentication);
    }
}
